/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import MovingPhotoView, { MovingPhotoViewRef } from '@hadss/react_native_moving_photo';
import React, { useCallback, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, TextInput, ColorValue } from 'react-native';
const TAG = 'MovingPhotoTest';
const getResizeMode = (index: number): 'contain' | 'cover' | 'stretch' | 'center' => {
  if (index === 1) {
    return 'contain';
  } else if (index === 2) {
    return 'center';
  } else if (index === 3) {
    return 'stretch';
  } else {
    return 'cover';
  }
};

const MovingPhotoPage = (): JSX.Element => {
  const [activeIndex, setActiveIndex] = useState(0);
  const [isMuted, setIsMuted] = useState(true);
  const [autoPlay, setIsAutoPlay] = useState(false);
  const [repeatPlay, setIsRepeatPlay] = useState(false);
  const [enableAnalyzer, setIsEnableAnalyzer] = useState(false);
  const [autoPlayPeriod, setAutoPlayPeriod] = useState<{
    startTime: number;
    endTime: number;
  }>();
  const [resizeMode, setResizeMode] = useState<'contain' | 'cover' | 'stretch' | 'center'>('cover');
  const [resizeIndex, setResizeIndex] = useState(1);
  const [source, setText] = useState('file://media/Photo/41/IMG_1758766363_031/IMG_20250925_101103.jpg');
  const photoRef = React.useRef<MovingPhotoViewRef>(null);
  const startPlayback = useCallback(() => {
    photoRef.current && photoRef.current.startPlayback();
  }, []);
  const stopPlayback = useCallback(() => {
    photoRef.current && photoRef.current.stopPlayback();
  }, []);
  const refreshMovingPhoto = useCallback(() => {
    photoRef.current && photoRef.current.refreshMovingPhoto();
  }, []);
  const setSource = useCallback((text: string) => {
    setText(text);
  }, []);
  const onComplete = useCallback(() => {
    console.log(TAG, 'onComplete');
  }, []);
  const onStart = useCallback(() => {
    console.log(TAG, 'onStart');
  }, []);
  const onPause = useCallback(() => {
    console.log(TAG, 'onPause');
  }, []);
  const onStop = useCallback(() => {
    console.log(TAG, 'onStop');
  }, []);
  const onFinish = useCallback(() => {
    console.log(TAG, 'onFinish');
  }, []);
  const onError = useCallback(() => {
    console.log(TAG, 'onError');
  }, []);
  const setMute = useCallback(() => {
    setIsMuted(!isMuted);
  }, [isMuted]);
  const setAutoPlay = useCallback(() => {
    setIsAutoPlay(!autoPlay);
  }, [autoPlay]);

  const setRepeatPlay = useCallback(() => {
    setIsRepeatPlay(!repeatPlay);
  }, [repeatPlay]);

  const setPeriod = useCallback(() => {
    setAutoPlayPeriod({ startTime: 300, endTime: 1000 });
  }, []);
  const setEnableAnalyzer = useCallback(() => {
    setIsEnableAnalyzer(!enableAnalyzer);
  }, [enableAnalyzer]);
  const setImageFill = useCallback(() => {
    setResizeIndex(resizeIndex + 1);
    setResizeMode(getResizeMode(resizeIndex % 4));
  }, [resizeIndex]);
  const dataList = [
    {
      id: 0,
      text: '设置静音: ' + isMuted,
      onPress: setMute,
    },
    {
      id: 1,
      text: '设置自动播放: ' + autoPlay,
      onPress: setAutoPlay,
    },
    {
      id: 2,
      text: '设置重复播放: ' + repeatPlay,
      onPress: setRepeatPlay,
    },
    {
      id: 3,
      text: '设置自动播放区间: ' + JSON.stringify(autoPlayPeriod),
      onPress: setPeriod,
    },
    {
      id: 4,
      text: '设置支持AI: ' + enableAnalyzer,
      onPress: setEnableAnalyzer,
    },
    {
      id: 5,
      text: '设置显示模式: ' + resizeMode,
      onPress: setImageFill,
    },
    {
      id: 6,
      text: '点击播放',
      onPress: startPlayback,
    },
    {
      id: 7,
      text: '点击停止',
      onPress: stopPlayback,
    },
    {
      id: 8,
      text: '点击刷新',
      onPress: refreshMovingPhoto,
    },
  ];

  const selectColor = (index: number): { bgColor: ColorValue; textColor: ColorValue } => {
    return {
      bgColor: activeIndex === index ? 'rgb(10, 89, 247)' : 'rgba(0, 0, 0, 0.05)',
      textColor: activeIndex === index ? 'white' : 'rgb(10, 89, 247)',
    };
  };
  const touchItem = (text: string, index: number, onPress: Function): JSX.Element => {
    const itemPress = (): void => {
      onPress();
      setActiveIndex(index);
    };
    return (
      <TouchableOpacity
        key={index + '--' + text}
        style={[{ backgroundColor: selectColor(index).bgColor }, styles.button]}
        onPress={itemPress}>
        <Text style={[{ color: selectColor(index).textColor }, styles.btnText]}>{text}</Text>
      </TouchableOpacity>
    );
  };

  return (
    <View style={styles.container}>
      <View style={styles.title}>
        <Text style={styles.titleText}>MovingPhoto Test</Text>
      </View>

      <ScrollView scrollEnabled={true} style={styles.scrollView} showsVerticalScrollIndicator={false}>
        <TextInput
          style={styles.textinput}
          multiline={true}
          onChangeText={setSource}
          value={source} // 设置输入框的当前值
          placeholder="file://media/Photo/41/IMG_1758766363_031/IMG_20250925_101103.jpg"
        />
        {dataList.map((item) => {
          return touchItem(item.text, item.id, item.onPress);
        })}
        <MovingPhotoView
          ref={photoRef}
          source={source}
          autoPlayPeriod={autoPlayPeriod}
          isMuted={isMuted}
          isAutoPlay={autoPlay}
          isRepeatPlay={repeatPlay}
          enableAnalyzer={enableAnalyzer}
          resizeMode={resizeMode ?? 'cover'}
          style={styles.photoStyle}
          onComplete={onComplete}
          onFinish={onFinish}
          onPause={onPause}
          onStart={onStart}
          onStop={onStop}
          onError={onError}
        />
      </ScrollView>
    </View>
  );
};

export default MovingPhotoPage;

const styles = StyleSheet.create({
  title: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    width: '100%',
    marginBottom: 16,
  },
  titleText: {
    fontSize: 30,
  },
  textinput: {
    backgroundColor: 'white',
    width: '100%',
    minHeight: 60,
    marginBottom: 16,
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 8,
    color: 'rgba(0, 0, 0, 0.6)',
  },
  photoStyle: {
    width: '100%',
    height: 400,
    marginBottom: 10,
  },
  container: {
    backgroundColor: '#F1F3F5',
    paddingHorizontal: 16,
    paddingTop: 72,
    justifyContent: 'flex-start',
    alignItems: 'center',
    width: '100%',
    height: '100%',
  },
  scrollView: {
    width: '100%',
    height: '100%',
  },
  button: {
    width: '100%',
    height: 40,
    borderRadius: 20,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 12,
  },
  btnText: {
    fontSize: 16,
    fontWeight: '500',
  },
});
